﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace WingMesLed
{
    public partial class FormMain : Form
    {
        public Dictionary<string, DeviceObj> DeviceObjs;
        public Dictionary<string, LedItem> LedLists = new Dictionary<string, LedItem>();
        public FormMain()
        {
            InitializeComponent();
            var str = System.IO.File.ReadAllText("deviceList.json");
            DeviceObjs = JsonConvert.DeserializeObject<Dictionary<string, DeviceObj>>(str);
            if (DeviceObjs is null) DeviceObjs = new Dictionary<string, DeviceObj>();
            RefreshDataGrid(first_run:true);
            timer1.Start();
        }

        private void RefreshDataGrid(bool first_run = false)
        {
            dataDeviceList.Rows.Clear();
            int i = 0;
            foreach (var item in DeviceObjs)
            {
                dataDeviceList.Rows.Add(item.Key, item.Value.deviceName);

                if (first_run)
                {
                    var led = new LedItem(item.Key);
                    led.Location = new Point(10, 5 + 50 * (i++));
                    led.lbDeviceName.Text = item.Value.deviceName;
                    tabPageDevice.Controls.Add(led);
                    LedLists.Add(item.Key, led);
                    led.Show();
                    led.Begin();
                }
                else
                {
                    if(LedLists.ContainsKey(item.Key))
                    {
                        LedLists[item.Key].lbDeviceName.Text = item.Value.deviceName;
                        i++;
                    }
                    else
                    {
                        var led = new LedItem(item.Key);
                        led.Location = new Point(10, 5 + 50 * (i++));
                        led.lbDeviceName.Text = item.Value.deviceName;
                        tabPageDevice.Controls.Add(led);
                        LedLists.Add(item.Key, led);
                        led.Show();
                        led.Begin();
                    }
                }
            }
        }

        private void btnAddDevice_Click(object sender, EventArgs e)
        {
            if(txtDeviceName.Text.Length == 0)
            {
                MessageBox.Show("请输入设备名称");
                return;
            }

            System.Net.IPAddress ip;
            bool ret = System.Net.IPAddress.TryParse(txtDeviceIP.Text, out ip);
            if(!ret)
            {
                MessageBox.Show("请输入合法的IP地址");
                return;
            }

            bool modify = false;
            if(modify = DeviceObjs.ContainsKey(txtDeviceIP.Text))
            {
                var result = MessageBox.Show("已存在该设备，是否修改?", "WARNING", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result != DialogResult.Yes)
                    return;
            }

            if (modify)
            {
                DeviceObjs[txtDeviceIP.Text] = new DeviceObj(txtDeviceName.Text, txtDeviceIP.Text);
            }
            else
            {
                DeviceObjs.Add(txtDeviceIP.Text, new DeviceObj(txtDeviceName.Text, txtDeviceIP.Text));
            }
            string dev_json = JsonConvert.SerializeObject(DeviceObjs, Formatting.Indented);
            using(var wr = new System.IO.StreamWriter("deviceList.json"))
            {
                wr.Write(dev_json);
            }

            RefreshDataGrid();
        }

        private void btnRemoveDevice_Click(object sender, EventArgs e)
        {
            if(DeviceObjs.ContainsKey(txtDeviceIP.Text))
            {
                DeviceObjs.Remove(txtDeviceIP.Text);
                string dev_json = JsonConvert.SerializeObject(DeviceObjs, Formatting.Indented);
                using (var wr = new System.IO.StreamWriter("deviceList.json"))
                {
                    wr.Write(dev_json);
                }

                RefreshDataGrid();
                if(LedLists.ContainsKey(txtDeviceIP.Text))
                {
                    tabPageDevice.Controls.Remove(LedLists[txtDeviceIP.Text]);
                    LedLists[txtDeviceIP.Text].modbusTcp.Dispose();
                    LedLists[txtDeviceIP.Text].Dispose();
                    LedLists.Remove(txtDeviceIP.Text);
                }
            }
        }

        private void dataDeviceList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataDeviceList.CurrentRow.Cells[0].Value is null)
                return;
            txtDeviceIP.Text = dataDeviceList.CurrentRow.Cells[0].Value.ToString();
            txtDeviceName.Text = dataDeviceList.CurrentRow.Cells[1].Value.ToString();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            var online = LedLists.Where(t => t.Value.modbusTcp.Connected).Count();
            var total = LedLists.Count();
            lbOnlineInfo.Text = $"{online}/{total}";
        }
    }
}
